//
//  MHActionSheetView.swift
//  Kool Carsaleman
//
//  Created by huang weiqiang on 2020/11/3.
//  Copyright © 2020 Kool Car. All rights reserved.
//

import UIKit

enum MHActionSheetViewType {
    case sheetViewDefault  //取消按钮在底部
    case allBtnAtTop      //取消按钮和确认按钮在顶部
}
typealias MHActionSheetViewObjectBlock = (AnyObject,_ selectIndex: NSInteger)->()
class MHActionSheetView: UIViewController {
    var tableView: UITableView!
    var dataArray:[Any] = []
    var bkgBtn: UIButton!
    var contentView: UIView! //装载tableView背景圆角时用
    var callObjBack: MHActionSheetViewObjectBlock!
    var titleStr: String = ""
    
    var headerView: UIView!
    var footerView: UIView!
    var selectIndex = 99999 //记录选中的
    var sheetType: MHActionSheetViewType = .sheetViewDefault
    override func viewDidLoad() {
        super.viewDidLoad()
        //背景蒙层
        self.view.backgroundColor = UIColor.clear
        bkgBtn = UIButton.init(type: UIButtonType.custom)
        bkgBtn.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
        bkgBtn.backgroundColor =  UIColor.init(R: 0, G: 0, B: 0, alpha: 0)
        bkgBtn.addTarget(self, action: #selector(hiddenActionView), for: .touchUpInside)
        self.view.addSubview(bkgBtn)
        
        ///
        self.contentView = UIView.init(frame: CGRect.init(x: 0, y: kScreenHeight, width: kScreenWidth, height: kScreenHeight))
        self.contentView.backgroundColor = UIColor.white
        self.bkgBtn.addSubview(self.contentView)
        
        self.headerView = self.setUpHeaderView()
        self.footerView = self.setUpFooterView()
        self.contentView.addSubview(self.headerView)
        self.contentView.addSubview(self.footerView)
        
        self.tableView = UITableView.init(frame: CGRect.init(x: 0, y: self.headerView.frame.maxY, width: kScreenWidth, height: kScreenHeight), style: .plain)
        self.tableView.register(MHActionSheetCell.self , forCellReuseIdentifier: "MHActionSheetCell")
        self.tableView.register(SelectSalemanSubCell.self , forCellReuseIdentifier: "SelectSalemanSubCell")
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.backgroundColor = UIColor.clear
        self.tableView.separatorStyle = .none
        self.tableView.separatorStyle = .none
        self.tableView.isScrollEnabled = false
        if #available(iOS 15, *) {
            self.tableView.sectionHeaderTopPadding = 0
        }
        self.tableView.bounces = true
        self.contentView.addSubview(self.tableView)
   
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.startAnimationAction()
    }
    
    ///顶部 TitleLabel有半圆
    func setUpHeaderView() -> UIView {
        let tempH: CGFloat = self.titleStr == "" ? 0 : 56
        let tempHeaderView = UIView.init(frame: CGRect.init(x: 0, y: kScreenHeight, width: kScreenWidth, height: tempH))
        if self.titleStr != "" {
            //做圆角背景
            tempHeaderView.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 56)
            tempHeaderView.backgroundColor = UIColor.white
            tempHeaderView.round(byRoundingCorners: UIRectCorner.init(arrayLiteral: .topLeft, .topRight), cornerRadi: 10)
            
            let tempTitleLab = UILabel.init(frame: CGRect.init(x: kScreenWidth/2 - 160, y: 0, width: 320, height: 56))
            tempTitleLab.backgroundColor = UIColor.clear
            tempTitleLab.textAlignment = .center
            tempTitleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
            tempTitleLab.textColor = Theme.titleLabColor
            tempTitleLab.numberOfLines = 0
            tempTitleLab.text = self.titleStr
            tempHeaderView.addSubview(tempTitleLab)
            
            let lineView = UIView.init(frame: CGRect.init(x: 0, y: tempHeaderView.frame.size.height - 0.5, width: kScreenWidth, height: 0.5))
            lineView.backgroundColor = UIColor.init(hex: 0xF2F7FA)
            tempHeaderView.addSubview(lineView)
            
            if self.sheetType == .allBtnAtTop {
                //取消按钮和确认按钮在顶部
                let cancelBtn = UIButton.init(frame: CGRect.init(x: 14, y: 8, width: 40, height: 40))
                cancelBtn.setTitle(MMLocalizedString("cancel", comment: "取消"), for: .normal)
                cancelBtn.setTitle(MMLocalizedString("cancel", comment: "取消"), for: .normal)
                cancelBtn.setTitleColor(Theme.mainColor, for: .normal)
                cancelBtn.setTitleColor(Theme.mainColor, for: .normal)
                cancelBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 16)
                cancelBtn.addTarget(self, action: #selector(hiddenActionView), for: .touchUpInside)
                tempHeaderView.addSubview(cancelBtn)
                
                let okBtn = UIButton.init(frame: CGRect.init(x: tempHeaderView.frame.size.width - 54, y: 8, width: 40, height: 40))
                okBtn.setTitle(MMLocalizedString("confirm", comment: "确定"), for: .normal)
                okBtn.setTitle(MMLocalizedString("confirm", comment: "确定"), for: .normal)
                okBtn.setTitleColor(Theme.mainColor, for: .normal)
                okBtn.setTitleColor(Theme.mainColor, for: .normal)
                okBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 16)
                okBtn.addTarget(self, action: #selector(okBtnAction), for: .touchUpInside)
                tempHeaderView.addSubview(okBtn)
            }
        }
        return tempHeaderView
    }
    
    ///确定
    @objc func okBtnAction(){
        if self.dataArray.count > self.selectIndex {
            let itemObj = self.dataArray[self.selectIndex] as AnyObject
            self.callObjBack?(itemObj, self.selectIndex)
            self.cancelBtnAction()
        }else{
            self.hiddenActionView()
        }
    }
    
    ///底部取消按钮
    func setUpFooterView() -> UIView {
        if self.sheetType == .sheetViewDefault {
            let tempH: CGFloat = 56 + IphoneXMarginBottom
            let tempFooterView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: tempH))
            tempFooterView.backgroundColor = UIColor.white
            //间隙
            
            let spaceView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 8))
            spaceView.backgroundColor = UIColor.init(hex: 0xF2F2F2)
            tempFooterView.addSubview(spaceView)
            //按钮
            let cancelBtn = UIButton.init(frame: CGRect.init(x: 0, y: 8, width: kScreenWidth, height: 56))
            cancelBtn.setTitle(MMLocalizedString("cancel", comment: "取消"), for: .normal)
            cancelBtn.setTitle(MMLocalizedString("cancel", comment: "取消"), for: .highlighted)
            cancelBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 18)
            cancelBtn.setTitleColor(UIColor.init(hex: 0xE8181A), for: .normal)
            cancelBtn.setTitleColor(UIColor.init(hex: 0xE8181A), for: .highlighted)
            cancelBtn.addTarget(self, action: #selector(cancelBtnAction), for: .touchUpInside)
            tempFooterView.addSubview(cancelBtn)
            return tempFooterView
        }else{
            let aView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: IphoneXMarginBottom))
            aView.backgroundColor = UIColor.init(hex: 0xF2F7FA)
            
            return aView
        }
    }
    
    ///页面展示动画
    @objc func startAnimationAction(){
        var tempHH: CGFloat = CGFloat(self.dataArray.count * 56)
        if tempHH > kScreenHeight/2 {
            tempHH = kScreenHeight/2
            self.tableView.isScrollEnabled = true
        }else{
            self.tableView.isScrollEnabled = true
        }
        self.tableView.frame.size.height = tempHH
        let headerFooter = self.headerView.frame.size.height + self.footerView.frame.size.height
        self.contentView.frame.size.height = tempHH + headerFooter
        self.contentView.round(byRoundingCorners: UIRectCorner.init(arrayLiteral: .topLeft, .topRight), cornerRadi: 6)

        self.headerView.frame.origin = CGPoint.init(x: 0, y: 0)
        self.tableView.frame.origin = CGPoint.init(x: 0, y: self.headerView.frame.maxY)
        self.footerView.frame.origin = CGPoint.init(x: 0, y: self.tableView.frame.maxY)
        let opts = UIViewAnimationOptions.curveEaseInOut
        UIView.animate(withDuration: 0.24, delay: 0, options: opts, animations: {
            self.bkgBtn.backgroundColor =  UIColor.init(R: 0, G: 0, B: 0, alpha: 0.7)
            self.contentView.frame.origin.y = kScreenHeight - tempHH - headerFooter
        }, completion: { _ in
            if self.titleStr == "" {
                //第一行做圆角处理
            }
            //移动到当前cell
            if self.dataArray.count > self.selectIndex {
                self.tableView.reloadData()
                if tempHH == kScreenHeight/2 {
                    self.tableView.scrollToRow(at: IndexPath.init(row: self.selectIndex, section: 0), at: .middle, animated: false)
                }else{
                    self.tableView.scrollToRow(at: IndexPath.init(row: self.selectIndex, section: 0), at: .top, animated: false)
                }
            }
        })
    }
    
    /// 隐藏,没有点添加到购物车按钮
    @objc func hiddenActionView(){
        let opts = UIViewAnimationOptions.curveEaseInOut
        UIView.animate(withDuration: 0.24, delay: 0, options: opts, animations: {
            self.bkgBtn.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0)
            self.contentView.frame.origin.y = kScreenHeight
        }, completion: { _ in
            self.dismiss(animated: false, completion: nil)
        })
    }
    
    @objc func cancelBtnAction(){
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            self.tableView.isUserInteractionEnabled = true
            self.hiddenActionView()
        }
    }
    
    //延迟执行
    @objc func selected()  {
        self.hiddenActionView()
    }
}


extension MHActionSheetView: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 56.0
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let tempHeaderView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 0.1))

        return tempHeaderView
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let tempFooterView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 0.1))
        tempFooterView.backgroundColor = UIColor.white
        return tempFooterView
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SelectSalemanSubCell", for: indexPath) as! SelectSalemanSubCell
        
        if self.titleStr == "" && indexPath.row == 0 {
            //第一行展示线
            cell.lineView.isHidden = false
        }else{
            cell.lineView.isHidden = true
        }
        
        if self.dataArray.count > indexPath.row {
            let itemModel = self.dataArray[indexPath.row]
            //一般的actionSheet
            cell.lineView.isHidden = false
            if self.selectIndex == indexPath.row {
                //记录选中状态
                cell.titleLab.textColor = Theme.mainColor
            }else{
                cell.titleLab.textColor = Theme.titleLabColor
            }
            
            
            if (itemModel as? StoreListModel) != nil {
                cell.titleLab.text = (itemModel as! StoreListModel).name ?? ""
            }else{
                cell.titleLab.text = (itemModel as! String)
            }
        }
        cell.selectionStyle = .none
        cell.clipsToBounds = true
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        self.selectIndex = indexPath.row
        
        self.okBtnAction()
//        //返回对像
//        if self.dataArray.count > self.selectIndex {
//            let itemObj = self.dataArray[indexPath.row] as AnyObject
//            self.callObjBack?(itemObj,indexPath.row)
//            self.cancelBtnAction()
//        }
    }
}
